//table2excel.js
//selector:tableId的数组;sheets:sheet的名字数组;filename:生成文件名字，后缀必须为xls
//调用方法   $.table2excel({selector:$(".test"),sheets: ['name1', 'name2'], filename:"testExport.xls"});
(function ($) {
    $.extend({ 
        table2excel: function (options) {
            tablesToExcel(options)
        }
    });

    defaults = {
        selector: 'table',
        sheets: [],
        filename: "table2excel.xls"
    };

    function tablesToExcel(options) {
        var uri = 'data:application/vnd.ms-excel; charset=UTF-8,'
            , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
    + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"></DocumentProperties>'
    + '<Styles>'
    + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
    + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
    + '<Style ss:ID="Bold"><Font ss:Bold="1"/></Style>'
    + '</Styles>'
    + '{worksheets}</Workbook>'
    , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{columns}{rows}</Table></Worksheet>'
    , tmplColumn = '<Column  ss:Width="{length}" />'
    , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
    , format = function (s, c) {
        return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; })
    },
  exclude_inputs = function (string) {
      var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i;
      return string.replace(/<input[^>]*>|<\/input>/gi,
          function myFunction(x) {
              var res = _patt.exec(x);
              if (res !== null && res.length >= 2) {
                  return res[2];
              } else {
                  return "";
              }
          });
  },
 exclude_img = function (string) {
     var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i;
     return string.replace(/<img[^>]*>/gi, function myFunction(x) {
         var res = _patt.exec(x);
         if (res !== null && res.length >= 2) {
             return res[2];
         } else {
             return "";
         }
     });
 },
    exclude_links = function (string) {
        return string.replace(/<a[^>]*>|<\/a>/gi, "");
    },
 getStrLength = function (str) {
     str= str.replace(/[\r\n]/g,"");
        var cArr = str.match(/[^\x00-\xff]/ig);
        return str.length + (cArr == null ? 0 : cArr.length);
    }
        var a;
        var ctx = "";
        var workbookXML = "";
        var worksheetsXML = "";
        var rowsXML = "";
        var columnsXml = "";
        var tables = [].slice.call(
typeof options.selector === 'string'
? document.querySelectorAll(options.selector)
: options.selector
);
        $(tables).each(function (i, table) {
            var columns=[]
            $(table).find('tr').each(function (r, rows) {
                if ($(rows).children()[0].localName == 'th') {
                    rowsXML += '<Row ss:StyleID="Bold">';
                } else {
                    rowsXML += '<Row>';
                }
                $(rows).find('th,td').each(function (c, cell) {
                    var dataFormula = $(cell).html();
                    dataFormula = exclude_img(dataFormula);
                    dataFormula = exclude_inputs(dataFormula);
                    dataFormula = exclude_links(dataFormula);
                    ctx = {
                        attributeStyleID: ''
                            , nameType: 'String'
                            , data: dataFormula
                            , attributeFormula: ''
                    };
                    rowsXML += format(tmplCellXML, ctx);
                    //th
                    if (cell.localName == "th") {
                        var initLength =getStrLength( dataFormula) * 7;
                        if (typeof columns[c] === "undefined" || $(columns[c]).attr("ss:Width") < getStrLength(dataFormula) * 7) {
                            initLength = getStrLength(dataFormula) * 7
                            ctx = {
                                length: initLength,
                            }
                            columns[c] = format(tmplColumn, ctx);
                        }
                    }
                    //td
                    if ($(columns[c]).attr("ss:Width") < getStrLength(dataFormula) * 5.12) {
                        ctx = {
                            length: getStrLength(dataFormula) * 5.12,
                        }
                        columns[c] = format(tmplColumn, ctx);
                    }
                });
                rowsXML += '</Row>'
            });

            var sheetName = 'Sheet' + (i+1);
            if (options.sheets != null) {
                sheetName = options.sheets[i] || sheetName;
            }
            $.each(columns, function (e, item) {
                columnsXml += item;
            })
            ctx = { columns: columnsXml, rows: rowsXML, nameWS: sheetName };
            worksheetsXML += format(tmplWorksheetXML, ctx);
            rowsXML = "";
            columnsXml = "";
        });
        ctx = { created: (new Date()).getTime(), worksheets: worksheetsXML };
        workbookXML = format(tmplWorkbookXML, ctx);
        var isIE = /*@cc_on!@*/false || !!document.documentMode; // this works with IE10 and IE11 both :)            
        if (isIE) {
            if (typeof Blob !== "undefined") {
                workbookXML = [workbookXML];
                var blob1 = new Blob(workbookXML, { type: "text/html" });
                window.navigator.msSaveBlob(blob1, options.filename);
            } else {
                txtArea1.document.open("text/html", "replace");
                txtArea1.document.write(workbookXML);
                txtArea1.document.close();
                txtArea1.focus();
                sa = txtArea1.document.execCommand("SaveAs", true, options.filename);
            }
        } else {
            var blob = new Blob([workbookXML], { type: "application/vnd.ms-excel" });
            window.URL = window.URL || window.webkitURL;
            link = window.URL.createObjectURL(blob);
            a = document.createElement("a");
            a.download = options.filename;
            a.href = link;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    };

})( jQuery);